<?php

namespace app\admin\controller\integral;
use app\admin\controller\base\Lecturer;
use app\admin\model\base\Subject;
use app\admin\model\Department;
use app\admin\model\finance\extract\Round;
use app\admin\model\finance\extract\School;
use app\admin\model\finance\extract\Week;
use app\common\controller\Backend;

use app\admin\model\Admin;
use app\admin\model\AuthDepartment;
use fast\Tree;
use PHPExcel_IOFactory;
use think\Cache;
use think\Db;
use think\session;

/**
 * 零售店管理
 *
 * @icon fa fa-circle-o
 */
class Zzw extends Backend
{
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\finance\extract\Week;
        $dept = GetBaseInfo('Dept');
        $groupList = collection(AuthDepartment::field('*,parentid as pid')->where('id','in',''.implode(',',$dept).'')->whereOr('parentid','in',''.implode(',',$dept).'')->select())->toArray();
        Tree::instance()->init($groupList);
        //权限
        $this->RoleFinance = GetRoleFinance();
        $groupdata = [];
        $result = [];
        if(!empty($this->RoleFinance['role'])){
            $groups = $this->auth->getGroups();
            $userid = \think\Session::get('admin')['userid'];
            $temp = [];
            foreach (explode(',',$this->RoleFinance['role']) as $m => $n){
                $childlist = Tree::instance()->getTreeList(Tree::instance()->getTreeArray(2));
                if($n == 2){
                    foreach ($childlist as $k => $v){
                        if(ValueExists($dept,$v['id'])){
                            $kee = TableListSqlQuery('Field'," `parentid` = '".$v['id']."' ",'id','hdyj_auth_department');
                            $kee = implode(',',array_column($kee,'id'));
                            $temp[$kee] = $v['name'];
                            unset($kee);
                        }else{
                            $temp[$v['id']] = $v['name'];
                        }
                    }
                }else{
                    foreach ($childlist as $k => $v){
                        if(ValueExists($dept,$v['id'])){
                            if($v['id'] == $n || $v['parentid'] == $n) {
                                $kee = TableListSqlQuery('Field'," `parentid` = '".$v['id']."' ",'id','hdyj_auth_department');
                                $kee = implode(',',array_column($kee,'id'));
                                $temp[$kee] = $v['name'];
                                unset($kee);
                            }
                        }else{
                            if($v['id'] == $n || $v['parentid'] == $n) $temp[$v['id']] = $v['name'];
                        }
                    }
                }
            }
            $groupdata = $temp;
        }
        //print_r($groupdata);die;
        $this->view->assign('groupdata', $groupdata);
        $this->view->assign("statusList", $this->model->getStatusList());
        $start_time = GenerateDate(\think\Config::get('finance.Generate_Week'))['start_time'];
        $end_time = GenerateDate(\think\Config::get('finance.Generate_Week'))['end_time'];
        $this->view->assign("DefaultsTime", $start_time.','.$end_time);
        $this->view->assign("DefaultsDate", date('Y'));
        $this->view->assign("DefaultsDateM", date('m'));
        $this->view->assign("divisionMethodList", $this->model->getDivisionMethodList());
        $this->view->assign("divisionMethodRoundList", $this->model->getDivisionMethodRoundList());
        $this->view->assign("Generate_Week", \think\Config::get('finance.Generate_Week'));

    }


    public function index()
    {
        $this->relationSearch = false;
        //设置过滤方法
        $this->request->filter(['strip_tags']);
        if ($this->request->isAjax()){
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')){
                return $this->selectpage();
            }
            $fi_where = $this->RoleFinance['where'];
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $total = $this->model
                ->where($where)
                ->where($fi_where)
                ->order($sort, $order)
                ->group('start_time')
                ->count();
            //	print_R($this->model->getLastSql());die;
            $list = $this->model
                ->where($where)
                ->where($fi_where)
                ->order($sort, $order)
                ->group('start_time')
                ->limit($offset, $limit)
                ->select();
            foreach ($list as $row) {
                $row->visible(['id','name','start_time','end_time','division_method','division_method_round','status','department_text','status_desc','createtime','updatetime']);
            }
            //print_r($this->model->getLastSql());die;
            $list = collection($list)->toArray();

            $result = array("total" => $total, "rows" => $list);

            return json($result);
        }
        return $this->view->fetch();
    }

    //统计,加外联积分
    public function plus($id,$isTrue=0){

        $rese = $this->reserve($id);

        //公司积分在此获取
        $pointer = $this->week_i($id) + $this->ykh_i($id) + $this->task_i($id) + $rese['pointer'];
        $out = new Outreach();
        $jifen = $out->jifen($id);//外联积分
        $sum=0;
        if ($jifen[1])$sum+=array_sum($jifen[1]);
        if ($isTrue==1){
            $jiangli=0;
            $inArr=array();
            $weekDb = new \app\admin\model\finance\extract\Week();
            $week = $weekDb->find($id);

            $arr=array("14"=>array('name'=>"东区"),
                array('name'=>"北区"),
                array("name"=>"西区"),
                array("name"=>"南区")
            );
            $depdb = new AuthDepartment();
            $j=0;
            $heji=0;
            $max=0;
            foreach ($arr as $k=>$v){
                $info = collection($depdb->where(array('parentid'=>$k))->select())->toArray();
                $jifen=0;
                foreach ($info as $key=>$val) {
                    $temp = 0;//积分
                    $ids = $weekDb->where(array('start_time' => $week['start_time'], 'end_time' => $week['end_time'], 'department' => $val['id']))->find();
                    if ($ids) {

                        $temp = $this->plus($ids['id']);//这里是有数据
                    } else {
                        $temp = 0;
                    }
                    $jifen += $temp;

                    $j++;
                }



                if ($heji < $jifen){//积分比较
                    $heji=$jifen;
                    $max=$k;//获取最大排名的大区
                    $inArr=array_column($info,'id');

                }

            }
            if (in_array($id,$inArr)){//奖励积分
                $sum+=100;
            }
        }


        return $pointer+$sum;


    }
    //大区排名
    public function daqu($ids){
        $weekDb = new \app\admin\model\finance\extract\Week();
        $week = $weekDb->find($ids);

        $arr=array("14"=>array('name'=>"东区"),
                    array('name'=>"北区"),
                    array("name"=>"西区"),
                    array("name"=>"南区")
        );
        $depdb = new AuthDepartment();
        $list=array();
        $totalTr=0;
        $j=0;
        $heji=0;
        $max=0;
        $ms=$msAr=$count=array();

        foreach ($arr as $k=>$v){
            $info = collection($depdb->where(array('parentid'=>$k))->select())->toArray();
            $jifen=0;

            foreach ($info as $key=>$val) {
                $temp = 0;//积分
                $ids = $weekDb->where(array('start_time' => $week['start_time'], 'end_time' => $week['end_time'], 'department' => $val['id']))->find();
                if ($ids) {

                    $temp = $this->plus($ids['id']);//这里是有数据
                } else {
                    $temp = 0;
                }
                $jifen += $temp;

                $list[$j]['diqu'] = $k;
                $list[$j]['jifen'] = $jifen;
                $list[$j]['key'] = $k;
                $list[$j]['jifen'] = $temp;
                $list[$j]['gongsi'] = $val['name'];
                $list[$j]['tushu'] = 0;//图书
                if ($key == 0) {
                    $list[$j]['row'] = count($info);//图书
                    $list[$j]['val'] = count($info);//图书
                    $ms[]=$j;

                 }
                $list[$j]['name']=$v['name'];
                $j++;
            }

            $msAr[] = $jifen;//图书
            $count[]=count($info);


            if ($heji < $jifen){//积分比较
                $heji=$jifen;
                $max=$k;//获取最大排名的大区
            }

        }
        $total3=$total4=$total5=0;
        //交换键值
        foreach ($ms as $k=>$v){
            $list[$v]['heji']=$msAr[$k];
            $list[$v]['pinjun']=round($msAr[$k]/$count[$k],2);
            $total3+=$count[$k];
            $total4+=$msAr[$k];
            $total5+=round($msAr[$k]/$count[$k],2);


        }
        $temp1=$temp2=array();
        $total=$total1=$total2=$total6=$total7=0;
        foreach ($list as $k=>$v){
            if ($v['key']==$max){

                $v['jiangli']=100;
                $temp1[]=$v;
            }else{
                $v['jiangli']=0;
                $temp2[]=$v;

            }
            $total6+=$v['jiangli'];
            $total+=$v['jifen'];
            $total1+=$v['tushu'];
            $total2+=$v['tushu']+$v['jifen'];
            $total7+=$v['jifen']+$v['tushu']+$v['jiangli'];
        }
        $merge=array_merge($temp1,$temp2);
        $this->assign('total',$total);
        $this->assign('total1',$total1);
        $this->assign('total2',$total2);
        $this->assign('total3',$total3);
        $this->assign('total4',$total4);
        $this->assign('total5',$total5);
        $this->assign('total6',$total6);
        $this->assign('total7',$total7);

        $this->assign('merge',$merge);
        return $this->view->fetch();

    }

    //积分排名
    public function ranking($ids){
        $weekDb = new \app\admin\model\finance\extract\Week();
        $week = $weekDb->find($ids);
        //获取当前几组

        $inteInfo = Db::name("integral_group")->where(array('starttime'=>$week['start_time'],'endtime'=>$week['end_time']))->find();
        $data = unserialize($inteInfo['data']);
        $info['data']=$data;
        $arr=array();
        foreach ($data as $key=>$v){
            foreach ($v as $k=>$val){

                $ids = $weekDb->where(array('start_time'=>$week['start_time'],'end_time'=>$week['end_time'],'department'=>$val))->find();
                if (empty($ids)){
                    $arr[$key][$val]=0;
                }else {
                    $id = $ids['id'];
                    $rese = $this->reserve($id);

                    //公司积分在此获取
                    $arr[$key][$val] = $this->week_i($id) + $this->ykh_i($id) + $this->task_i($id) + $rese['pointer'];
                }
            }
        }

        $list=array();
        $temp=0;
        $j=0;
        //获取二维数组的长度值
        foreach ($arr as $key=>$val){
            arsort($val);

            if (count($val) > $temp){
                $temp=count($val);
            }
            $s=0;
            foreach($val as $k=>$v){
                $list[$j][$s]['key']=$k;
                $list[$j][$s]['val']=$v;
                $s++;
            }
            $j++;
        }

        $this->assign('count',$temp);
        //组数统计
        $this->assign('scount',count($data));
        $this->assign("inteInfo",$inteInfo);
        $this->assign('list',$list);
        $this->assign('info',$info);
        $authList=$this->authList();
        $this->assign('dep',$authList);

        return $this->view->fetch();

    }
    protected function authList(){
        if(!$authList = Cache::get('zzwDep'))
        {

            $authD = new AuthDepartment();
            $authList = array_column($authD->where("parentid IN (14,15,16,17)")->field('id,name,delete_status')->select()->toArray(),null,'id');
            Cache::set('zzwDep',$authList,589400);//7天有效
        }
        return $authList;


    }
    /*
     * 周次分组
     *
    */
    public function fenzu($ids){
        $weekDb = new \app\admin\model\finance\extract\Week();
        $week = $weekDb->find($ids);

        if ($this->request->isPost() && $this->request->isAjax()) {
            $post = $this->request->post("row/a");


            $array = array();

            foreach ($post as $k => $v) {


                if ($this->thecks($v)) {

                    $array[$k] = $v;

                }
            }

            if (is_array($array) && $array){

                $data['starttime']=$week['start_time'];
                $data['endtime']=$week['end_time'];

                $data['data'] = serialize($array);

                if ($inteInfo = Db::name("integral_group")->field('id')->where(array('starttime'=>$week['start_time'],'endtime'=>$week['end_time']))->find()){
                    $id = $inteInfo['id'];
                    db('integral_group')->where('id',$id)->update($data);

                }else {
                    $a = session::get('admin');

                    $data['username'] = $a['username'];
                    $data['inputtime']=time();
                    Db::name("integral_group")->insert($data);
                }
                $this->success("添加成功");
            }else{
                $this->error("请添加分组");
            }


        }
            $info = Db::name("integral_group")->where(array('starttime'=>$week['start_time'],'endtime'=>$week['end_time']))->find();
            $this->assign('info',$info);
            return $this->view->fetch();
    }
    //应开会周不开会或开会不足
    protected function ykh_i($id){
        if (!$id) return false;
        $dbSea = new \app\admin\model\finance\extract\Season;
        $dbSchD = new \app\admin\model\finance\extract\school\Data;

        $values = collection($dbSea->where(array('extract_week'=>$id))->order('id asc')->select()->toArray());
        $num = count($values);
        $pointer=0;
        if ($num > 0){
            $wDb = new Week();
            $weekData = $wDb->where(array('id'=>$id))->field('start_time')->find();
            $wId=$weekData['start_time'];
            list($y,$m,$d)=explode('-',$wId);
            //10.1期间
            if ($m==10 && intval($d) <=7){
                if ($num >=8){
                    $pointer=20;
                }
            }else {
                $pointer = $num * 5;
            }
        }
        return $pointer;
    }
    protected function thecks($val){

        if(is_array($val) && $val[0]!=''){

            return true;
        }

        return false;
    }
    public function index2(){

        //周开场词积分




        //当前是否为关联查询
        $this->relationSearch = false;
        //设置过滤方法
        $this->request->filter(['strip_tags']);
        if ($this->request->isAjax())
        {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')){
                return $this->selectpage();
            }

            $fi_where = $this->RoleFinance['where'];

            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            //print_R($where);die;
            $total = $this->model
                ->where($where)
                ->where($fi_where)
                ->order($sort, $order)
                ->count();
            //	print_R($this->model->getLastSql());die;
            $list = $this->model
                ->where($where)
                ->where($fi_where)
                ->order($sort, $order)
                ->limit($offset, $limit)
                ->select();


            foreach ($list as $row) {

                 $row->visible(['id','name','start_time','end_time','division_method','division_method_round','status','department_text','status_desc','createtime','updatetime']);


            }


            //print_r($this->model->getLastSql());die;
            $list = collection($list)->toArray();
            $arr=array();
            foreach ($list as $k=>$row){
                $list[$k]['week_i']=$this->week_i($row['id']);
                $list[$k]['w_task']=$this->task_i($row['id']);
                $list[$k]['ykh_i'] = $this->ykh_i($row['id']);
                $arr=$this->reserve($row['id']);
                $list[$k]['reserve'] = $arr['pointer'];

            }

            $result = array("total" => $total, "rows" => $list);

            return json($result);
        }
        return $this->view->fetch();
    }
    public function jifen($id,$isTrue=0){

    }
    protected function get_school($id){
        if (!$id)return '';
        $scDb = new \app\admin\model\School();
        $info = $scDb->field('name')->find($id);
        if ($info)return $info['name'];
        return '';
    }
    //获取科目名称
    protected  function get_subject($id){
        $leDb = new Subject();

        $info = $leDb->field('name')->find($id);
        if ($info)return $info['name'];
        return '';
    }
    //获取老师名称
    protected  function get_lecturer($id){
        $leDb = new \app\admin\model\base\Lecturer();
        $info = $leDb->field('name')->find($id);
        if ($info)return $info['name'];
        return '';
    }
    //判断当前是否是地级市
    protected function get_fenlei($province,$area_text){
        $sub_arae = mb_substr($area_text,-1,1,'utf8');
        if(in_array($province,array(1,19,801))){
            return "地级市";
        }else{
            if ($sub_arae=="区"){
                return "地级市";

            }else{
                return "县级市";

            }
        }
    }
    public function paiming($ids){
        $weekDb = new \app\admin\model\finance\extract\Week();
        $week = $weekDb->find($ids);
        $bt=$week['name'].'排名';
        $arr=array("14"=>array('name'=>"东区"),
            array('name'=>"北区"),
            array("name"=>"西区"),
            array("name"=>"南区")
        );
        $depdb = new AuthDepartment();
        $list=array();
        $totalTr=0;
        $j=0;
        $heji=0;
        $max=0;
        $ms=$msAr=$count=array();

        foreach ($arr as $k=>$v){
            $info = collection($depdb->where(array('parentid'=>$k))->select())->toArray();
            $jifen=0;

            foreach ($info as $key=>$val) {
                $temp = 0;//积分
                $ids = $weekDb->where(array('start_time' => $week['start_time'], 'end_time' => $week['end_time'], 'department' => $val['id']))->find();
                if ($ids) {

                    $temp = $this->plus($ids['id']);//这里是有数据
                } else {
                    $temp = 0;
                }
                $jifen += $temp;

                $list[$j]['diqu'] = $k;
                $list[$j]['jifen'] = $jifen;
                $list[$j]['key'] = $k;
                $list[$j]['jifen'] = $temp;
                $list[$j]['gongsi'] = $val['name'];
                $list[$j]['tushu'] = 0;//图书
                if ($key == 0) {
                    $list[$j]['row'] = count($info);//图书
                    $list[$j]['val'] = count($info);//图书
                    $ms[]=$j;

                }
                $list[$j]['name']=$v['name'];
                $j++;
            }

            $msAr[] = $jifen;//图书
            $count[]=count($info);


            if ($heji < $jifen){//积分比较
                $heji=$jifen;
                $max=$k;//获取最大排名的大区
            }

        }
        $total3=$total4=$total5=0;
        //交换键值
        foreach ($ms as $k=>$v){
            $list[$v]['heji']=$msAr[$k];
            $list[$v]['pinjun']=round($msAr[$k]/$count[$k],2);
            $total3+=$count[$k];
            $total4+=$msAr[$k];
            $total5+=round($msAr[$k]/$count[$k],2);
        }
        $temp1=$temp2=array();
        $total=$total1=$total2=$total6=$total7=0;
        foreach ($list as $k=>$v){
            if ($v['key']==$max){

                $v['jiangli']=100;
                $temp1[]=$v;
            }else{
                $v['jiangli']=0;
                $temp2[]=$v;

            }
            $total6+=$v['jiangli'];
            $total+=$v['jifen'];
            $total1+=$v['tushu'];
            $total2+=$v['tushu']+$v['jifen'];
            $total7+=$v['jifen']+$v['tushu']+$v['jiangli'];
        }
        $merge=array_merge($temp1,$temp2);

        $objPHPExcel = new \PHPExcel();
        // 设置文档的相关信息
        $objPHPExcel->getProperties()->setCreator("宏达一甲")/*设置作者*/
        ->setLastModifiedBy("宏达一甲")/*最后修改*/
        ->setTitle($bt)/*题目*/
        ->setSubject($bt)/*主题*/
        ->setDescription($bt)/*描述*/
        ->setKeywords($bt)/*关键词*/
        ->setCategory($bt);/*类别*/
        $objPHPExcel->getActiveSheet()->setTitle($bt);
        $objPHPExcel->setActiveSheetIndex(0);
        //纸张方向和大小 为A4横向
        $objPHPExcel->getActiveSheet()->getPageSetup()->setOrientation(\PHPExcel_Worksheet_PageSetup::ORIENTATION_LANDSCAPE);
        $objPHPExcel->getActiveSheet()->getPageSetup()->setPaperSize(\PHPExcel_Worksheet_PageSetup::PAPERSIZE_A4);
        //浏览器交互 导出

        $objPHPExcel->getDefaultStyle()->getFont()->setName('微软雅黑');//字体
        /*设置表头*/
        $objPHPExcel->getActiveSheet()->mergeCells('A1:P1');//合并第一行的单元格
        $objPHPExcel->getDefaultStyle()->getAlignment()->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
        $objPHPExcel->getDefaultStyle()->getAlignment()->setVertical(\PHPExcel_Style_Alignment::VERTICAL_CENTER);
        $objPHPExcel->getDefaultStyle()->getFont()->setName('微软雅黑');//字体
        /*设置表头*/
        $objPHPExcel->getActiveSheet()->mergeCells('A1:P1');//合并第一行的单元格
        $objPHPExcel->getDefaultStyle()->getAlignment()->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
        $objPHPExcel->getDefaultStyle()->getAlignment()->setVertical(\PHPExcel_Style_Alignment::VERTICAL_CENTER);

        $objPHPExcel->setActiveSheetIndex(0)->setCellValue('A1', $bt);//标题
        $objPHPExcel->getActiveSheet()->getRowDimension('1')->setRowHeight(30);      // 第一行的默认高度
        $objPHPExcel->getActiveSheet()->getRowDimension('2')->setRowHeight(30);      // 第一行的默认高度

        $objPHPExcel->getActiveSheet()->getColumnDimension('A')->setWidth(20);
        $objPHPExcel->getActiveSheet()->getColumnDimension('B')->setWidth(15);
        $objPHPExcel->getActiveSheet()->getColumnDimension('C')->setWidth(23);
        $objPHPExcel->getActiveSheet()->getColumnDimension('D')->setWidth(26);
        $objPHPExcel->getActiveSheet()->getColumnDimension('E')->setWidth(21);
        $objPHPExcel->getActiveSheet()->getColumnDimension('F')->setWidth(10);
        $objPHPExcel->getActiveSheet()->getColumnDimension('G')->setWidth(10);
        $objPHPExcel->getActiveSheet()->getColumnDimension('H')->setWidth(27);
        $objPHPExcel->getActiveSheet()->getColumnDimension('I')->setWidth(25);
        $objPHPExcel->getActiveSheet()->getColumnDimension('J')->setWidth(10);
        $objPHPExcel->getActiveSheet()->getColumnDimension('K')->setWidth(21);
        $myrow=2;
        $objPHPExcel->setActiveSheetIndex(0)  //设置一张sheet为活动表 添加表头信息
        ->setCellValue('A' . $myrow, '序号')
            ->setCellValue('B' . $myrow, '区域')
            ->setCellValue('C' . $myrow, '市场')
            ->setCellValue('D' . $myrow, '市场总积分')
            ->setCellValue('E' . $myrow, '图书经理积分')
            ->setCellValue('F' . $myrow, '合计总积分')
            ->setCellValue('G' . $myrow, '分公司数量')
            ->setCellValue('H' . $myrow, '大区积分合计')
            ->setCellValue('I' . $myrow, '大区周平均积分')
            ->setCellValue('J' . $myrow, '积分奖励')
            ->setCellValue('K' . $myrow, '奖励后积分');
        $end=count($merge)+3;
        $objPHPExcel->getActiveSheet()->getRowDimension($end)->setRowHeight(30);      // 第一行的默认高度

        $objPHPExcel->setActiveSheetIndex(0)  //设置一张sheet为活动表 添加表头信息
        ->setCellValue('A' . $end, '')
            ->setCellValue('B' . $end, '合计')
            ->setCellValue('C' . $end, '')
            ->setCellValue('D' . $end, $total)
            ->setCellValue('E' . $end, $total1)
            ->setCellValue('F' . $end, $total2)
            ->setCellValue('G' . $end, $total3)
            ->setCellValue('H' . $end, $total4)
            ->setCellValue('I' . $end, $total5)
            ->setCellValue('J' . $end, $total6)
            ->setCellValue('K' . $end, $total7);
        $myrow=3;
        foreach ($merge as $k=>$v){
            if (isset($v['row'])) {
                $objPHPExcel->getActiveSheet()->setCellValue('G' . ($myrow + $k), $v['val']);
                $objPHPExcel->getActiveSheet()->mergeCells('G'. ($k + $myrow) . ':G'. ($myrow + $k + $v['row'] - 1));
                $objPHPExcel->getActiveSheet()->setCellValue('H' . ($myrow + $k), $v['heji']);
                $objPHPExcel->getActiveSheet()->mergeCells('H'. ($k + $myrow) . ':H'. ($myrow + $k + $v['row'] - 1));

                $objPHPExcel->getActiveSheet()->setCellValue('I' . ($myrow + $k), $v['pinjun']);
                $objPHPExcel->getActiveSheet()->mergeCells('I'. ($k + $myrow) . ':I'. ($myrow + $k + $v['row'] - 1));


            }
            $objPHPExcel->setActiveSheetIndex(0)  //设置一张sheet为活动表 添加表头信息
            ->setCellValue('A' . ($myrow+$k), $k+1)
                ->setCellValue('B' .($myrow+$k), $v['name'])
                ->setCellValue('C' . ($myrow+$k), str_replace('分公司','',$v["gongsi"]))
                ->setCellValue('D' . ($myrow+$k), $v['jifen'])
                ->setCellValue('E' . ($myrow+$k), $v['tushu'])
                ->setCellValue('F' . ($myrow+$k), $v['tushu']+$v['jifen'])

                ->setCellValue('J' . ($myrow+$k), $v['jiangli'])
                ->setCellValue('K' . ($myrow+$k), $v['tushu']+$v['jiangli']+$v['jifen']);
            $objPHPExcel->getActiveSheet()->getRowDimension('' . $k+$myrow)->setRowHeight(25);

        }
        /*var_dump($merge);
        exit;*/
        header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
        header('Content-Disposition: attachment;filename="'.$bt.'".xlsx');
        header('Cache-Control: max-age=0');
        // If you're serving to IE 9, then the following may be needed
        header('Cache-Control: max-age=1');

        // If you're serving to IE over SSL, then the following may be needed
        header('Expires: Mon, 26 Jul 1997 05:00:00 GMT'); // Date in the past
        header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . ' GMT'); // always modified
        header('Cache-Control: cache, must-revalidate'); // HTTP/1.1
        header('Pragma: public'); // HTTP/1.0
        $objWriter = \PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
        $objWriter->save('php://output');
        exit;
    }
    /*
     * 导出
     *
     * */
    public function excel($ids){
        $dbSea = new \app\admin\model\finance\extract\Season;
        $dbSchD = new \app\admin\model\finance\extract\school\Data;
        $wkDb = new Week();
        $out = new Outreach();
        $jifen = $out->jifen(16);
        $jiba = array();

        foreach ($jifen[0] as $v){
            $jiba[]=$v;
        }
        $jibaTotal=0;
        foreach($jifen[1] as $v){
            $jibaTotal+=$v;
        }

        $weekInfo = $wkDb->field('name,department')->find($ids);

        $values = $dbSea->where(array('extract_week'=>$ids))->order('id asc')->select()->toArray();
        $uDb=new Admin();
        $dbSch= new \app\admin\model\finance\extract\School;
        $totalTr=0;
        $arr=array();
        $j=0;
        $rankDef=array("1"=>"省会前十","地级前三","县级第一");
        $rows=array();

        $rows['cols_1']=$weekInfo['name'];
        $rows['cols_2']=$this->week_i($ids);
        $rows['cols_3']=$this->ykh_i($ids);
        $rows['cols_4']=$this->task_i($ids);
        $rows['cols_5']=$this->reserve($ids);
        $rows['cols_6']=round($rows['cols_2'],1)+round($rows['cols_3'],1)+round($rows['cols_4'],1)+round($rows['cols_5']['pointer'],1);
        foreach ($values as $key=>$val){
            $data = $dbSch->where(array('season_id'=>$val['id']))->select()->toArray();
            $count=count($data);

            $arr['cols_1'][$totalTr]['row']=$count;
            $arr['cols_1'][$totalTr]['val']=$val['season_time'];
            $arr['cols_2'][$totalTr]['row']=$count;
            $arr['cols_2'][$totalTr]['val']=$val['province_text'].' '.$val['city_text'].' '.$val['area_text'];
            $arr['cols_3'][$totalTr]['row']=$count;
            $arr['cols_3'][$totalTr]['val']=$this->get_fenlei($val['province'],$val['area_text']);
            $arr['cols_4'][$totalTr]['row']=$count;
            $arr['cols_4'][$totalTr]['val']=$this->get_lecturer($val['lecturer_id']);
            $arr['cols_5'][$totalTr]['row']=$count;
            $arr['cols_5'][$totalTr]['val']=$this->get_subject($val['subject_id']);
            $arr['cols_6'][$totalTr]['row']=$count;
            $arr['cols_6'][$totalTr]['val']=$val['reg_level'].'类';
            if ($data){
                $info=array();
                foreach($data as $v){
                    $arr['cols_7'][$j]=$this->get_school($v['school_id']);
                    $info= $dbSchD->where(array('extract_school'=>$v['id'],'type'=>1))->field('userid')->select()->toArray();


                    if ($info){
                        $uname=[];
                        foreach ($info as $d){
                            $a='';
                            if ($d['userid']!=null) {
                                $a=$uDb->field('username,is_zhengshi')->where(array('userid'=>$d['userid']))->find();
                                $uname[]=$a['username'].'/'.($a['is_zhengshi']==1 ? '新外联' : '老外联');
                            }
                        }
                        $arr['cols_8'][$j]=implode('-',$uname);

                    }else{
                        $arr['cols_8'][$j]='';
                    }
                    $arr['cols_9'][$j]= $v['level']==null ? '': $v['level'].'类';
                    $arr['cols_10'][$j]= $rankDef[$v['ranking_level']==null ? "1" : $v['ranking_level']];
                    $arr['cols_11'][$j]= $v['coming_num'];
                    $arr['cols_12'][$j]= $v['gift_books'];
                    $arr['cols_13'][$j]= $v['people_num'];

                    $j++;
                }

            }
            $totalTr+=count($data);

        }
        $authList = $this->authList();

        $rows['title']=$authList[$weekInfo['department']]['name']."积分";
        $bt=$rows['title'].$rows['cols_1'];
        $authList = $this->authList();
        $objPHPExcel = new \PHPExcel();
        // 设置文档的相关信息
        $objPHPExcel->getProperties()->setCreator("宏达一甲")/*设置作者*/
        ->setLastModifiedBy("宏达一甲")/*最后修改*/
        ->setTitle($bt)/*题目*/
        ->setSubject($bt)/*主题*/
        ->setDescription($bt)/*描述*/
        ->setKeywords($bt)/*关键词*/
        ->setCategory($bt);/*类别*/
        $objPHPExcel->getActiveSheet()->setTitle($bt);
        $objPHPExcel->setActiveSheetIndex(0);
        //纸张方向和大小 为A4横向
        $objPHPExcel->getActiveSheet()->getPageSetup()->setOrientation(\PHPExcel_Worksheet_PageSetup::ORIENTATION_LANDSCAPE);
        $objPHPExcel->getActiveSheet()->getPageSetup()->setPaperSize(\PHPExcel_Worksheet_PageSetup::PAPERSIZE_A4);
        //浏览器交互 导出

        $objPHPExcel->getDefaultStyle()->getFont()->setName('微软雅黑');//字体
        /*设置表头*/
        $objPHPExcel->getActiveSheet()->mergeCells('A1:P1');//合并第一行的单元格
        $objPHPExcel->getDefaultStyle()->getAlignment()->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
        $objPHPExcel->getDefaultStyle()->getAlignment()->setVertical(\PHPExcel_Style_Alignment::VERTICAL_CENTER);
        $objPHPExcel->getActiveSheet()->getStyle('A1')->getAlignment()->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_LEFT);
        $objPHPExcel->getActiveSheet()->getStyle('A'.($totalTr+3).'')->getAlignment()->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_LEFT);

        $objPHPExcel->getActiveSheet()->mergeCells('A'.($totalTr+3).':P'.($totalTr+3).'');//合并第一行的单元格

        $objPHPExcel->setActiveSheetIndex(0)->setCellValue('A'.($totalTr+3), "总积分:" .(round($rows['cols_6']+$jibaTotal,2))."公司积分+外联总积分");//标题

        $objPHPExcel->setActiveSheetIndex(0)->setCellValue('A1', $bt);//标题
        $objPHPExcel->getActiveSheet()->getRowDimension('1')->setRowHeight(30);      // 第一行的默认高度
        $objPHPExcel->getActiveSheet()->getRowDimension('2')->setRowHeight(40);      // 第一行的默认高度
        $objPHPExcel->getActiveSheet()->getRowDimension(($totalTr+3))->setRowHeight(40);      // 第一行的默认高度

        $objPHPExcel->getActiveSheet()->getColumnDimension('A')->setWidth(20);
        $objPHPExcel->getActiveSheet()->getColumnDimension('B')->setWidth(15);
        $objPHPExcel->getActiveSheet()->getColumnDimension('C')->setWidth(23);
        $objPHPExcel->getActiveSheet()->getColumnDimension('D')->setWidth(26);
        $objPHPExcel->getActiveSheet()->getColumnDimension('E')->setWidth(21);
        $objPHPExcel->getActiveSheet()->getColumnDimension('F')->setWidth(10);
        $objPHPExcel->getActiveSheet()->getColumnDimension('G')->setWidth(10);
        $objPHPExcel->getActiveSheet()->getColumnDimension('H')->setWidth(27);
        $objPHPExcel->getActiveSheet()->getColumnDimension('I')->setWidth(25);
        $objPHPExcel->getActiveSheet()->getColumnDimension('J')->setWidth(10);
        $objPHPExcel->getActiveSheet()->getColumnDimension('K')->setWidth(21);
        $objPHPExcel->getActiveSheet()->getColumnDimension('L')->setWidth(10);
        $objPHPExcel->getActiveSheet()->getColumnDimension('M')->setWidth(12);
        $objPHPExcel->getActiveSheet()->getColumnDimension('N')->setWidth(10);
        $objPHPExcel->getActiveSheet()->getColumnDimension('O')->setWidth(25);
        $objPHPExcel->getActiveSheet()->getColumnDimension('P')->setWidth(25);
        $objPHPExcel->getActiveSheet()->getColumnDimension('Q')->setWidth(15);
        $objPHPExcel->getActiveSheet()->getColumnDimension('R')->setWidth(21);
        $objPHPExcel->getActiveSheet()->getColumnDimension('S')->setWidth(21);
        $objPHPExcel->getActiveSheet()->getColumnDimension('T')->setWidth(21);
        $objPHPExcel->getActiveSheet()->getColumnDimension('U')->setWidth(21);
        $objPHPExcel->getActiveSheet()->getColumnDimension('V')->setWidth(21);
        $objPHPExcel->getActiveSheet()->getColumnDimension('W')->setWidth(21);

        $objPHPExcel->getActiveSheet()->getColumnDimension('X')->setWidth(21);
        $objPHPExcel->getActiveSheet()->getColumnDimension('Y')->setWidth(21);
        $objPHPExcel->getActiveSheet()->getColumnDimension('Z')->setWidth(21);
        $objPHPExcel->getActiveSheet()->getColumnDimension('AA')->setWidth(21);
        $objPHPExcel->getActiveSheet()->getColumnDimension('AB')->setWidth(21);
        $objPHPExcel->getActiveSheet()->getColumnDimension('AC')->setWidth(21);
        $objPHPExcel->getActiveSheet()->getColumnDimension('AD')->setWidth(21);
        $objPHPExcel->getActiveSheet()->getColumnDimension('AE')->setWidth(21);
        $objPHPExcel->getActiveSheet()->getColumnDimension('AF')->setWidth(31);


        ////第二行的内容和格式
        $myrow=2;
        $objPHPExcel->setActiveSheetIndex(0)  //设置一张sheet为活动表 添加表头信息
        ->setCellValue('A' . $myrow, '周次')
            ->setCellValue('B' . $myrow, '开会时间')
            ->setCellValue('C' . $myrow, '开会地区')
            ->setCellValue('D' . $myrow, '地区分类（地级市/县级市）')
            ->setCellValue('E' . $myrow, '讲师')
            ->setCellValue('F' . $myrow, '科目')
            ->setCellValue('G' . $myrow, '地区类别')
            ->setCellValue('H' . $myrow, '学校名称')
            ->setCellValue('I' . $myrow, '外联姓名/老/新')
            ->setCellValue('J' . $myrow, '学校分类')
            ->setCellValue('K' . $myrow, '本地学校排名')
            ->setCellValue('L' . $myrow, '学校人数')
            ->setCellValue('M' . $myrow, '学校发书数量')
            ->setCellValue('N' . $myrow, '来人数')
            ->setCellValue('O' . $myrow, '跑学校来人积分（合跑不另加分）')
            ->setCellValue('P' . $myrow, '跑下学校来人率（来人数/学校人数）')
            ->setCellValue('Q' . $myrow, '销售积分')
            ->setCellValue('R' . $myrow, '发书来人率积分')
            ->setCellValue('S' . $myrow, '来人发书率（来人数/学校发书数）30%以上')
            ->setCellValue('T' . $myrow, 'A类学校来人积分')
            ->setCellValue('U' . $myrow, '新外联跑学校销售积分')
            ->setCellValue('V' . $myrow, '奖励积分')
            ->setCellValue('W' . $myrow, '外联积分合计')

            ->setCellValue('X' . $myrow, '周开场次积分')
            ->setCellValue('Y' . $myrow, '应开会周不开会或开会不足')
            ->setCellValue('Z' . $myrow, '周任务积分')
            ->setCellValue('AA' . $myrow, '会场无事故积分')
            ->setCellValue('AB' . $myrow, '学校建设积分')
            ->setCellValue('AC' . $myrow, '关注积分')
            ->setCellValue('AD' . $myrow, '取预定积分')
            ->setCellValue('AE' . $myrow, '会后图书销售积分')
            ->setCellValue('AF' . $myrow, '减分项')

        ;
        $beginRow=3;
        $endRow=3+$totalTr;
        $objPHPExcel->getActiveSheet()->setCellValue('A'.$beginRow,$rows['cols_1']);
        $objPHPExcel->getActiveSheet()->mergeCells('A'.$beginRow.':A'.($endRow-1).'');
        $objPHPExcel->getActiveSheet()->setCellValue('X'.$beginRow,$rows['cols_2']);
        $objPHPExcel->getActiveSheet()->mergeCells('X'.$beginRow.':X'.($endRow-1).'');
        $objPHPExcel->getActiveSheet()->setCellValue('Y'.$beginRow,$rows['cols_3']);
        $objPHPExcel->getActiveSheet()->mergeCells('Y'.$beginRow.':Y'.($endRow-1).'');
        $objPHPExcel->getActiveSheet()->setCellValue('Z'.$beginRow,$rows['cols_4']);
        $objPHPExcel->getActiveSheet()->mergeCells('Z'.$beginRow.':Z'.($endRow-1).'');
        $objPHPExcel->getActiveSheet()->setCellValue('AA'.$beginRow,$rows['cols_5']['arr']['index_1']);
        $objPHPExcel->getActiveSheet()->mergeCells('AA'.$beginRow.':AA'.($endRow-1).'');
        $objPHPExcel->getActiveSheet()->setCellValue('AB'.$beginRow,$rows['cols_5']['arr']['index_2']);
        $objPHPExcel->getActiveSheet()->mergeCells('AB'.$beginRow.':AB'.($endRow-1).'');
        $objPHPExcel->getActiveSheet()->setCellValue('AC'.$beginRow,$rows['cols_5']['arr']['index_3']);
        $objPHPExcel->getActiveSheet()->mergeCells('AC'.$beginRow.':AC'.($endRow-1).'');
        $objPHPExcel->getActiveSheet()->setCellValue('AD'.$beginRow,$rows['cols_5']['arr']['index_4']);
        $objPHPExcel->getActiveSheet()->mergeCells('AD'.$beginRow.':AD'.($endRow-1).'');
        $objPHPExcel->getActiveSheet()->setCellValue('AE'.$beginRow,$rows['cols_5']['arr']['index_5']);
        $objPHPExcel->getActiveSheet()->mergeCells('AE'.$beginRow.':AE'.($endRow-1).'');
        $objPHPExcel->getActiveSheet()->setCellValue('AF'.$beginRow,$rows['cols_5']['arr']['index_6']);
        $objPHPExcel->getActiveSheet()->mergeCells('AF'.$beginRow.':AF'.($endRow-1).'');
        $strArr=array("1"=>"B","C","D","E","F","G","H");
        for($i=0;$i<$totalTr;$i++) {
          for ($j = 1; $j <= 6; $j++) {
                if ($cols = cols('cols_' . $j, $i, $arr)) {
                    $objPHPExcel->getActiveSheet()->setCellValue($strArr[$j].($beginRow+$i),$cols['val']);
                    $objPHPExcel->getActiveSheet()->mergeCells($strArr[$j].($i+$beginRow).':'.$strArr[$j].($beginRow+$i+$cols['row']-1));

                }
            }
        $objPHPExcel->setActiveSheetIndex(0)
                ->setCellValue('H' . ($i+3), $arr['cols_7'][$i])
                ->setCellValue('I' . ($i+3), $arr['cols_8'][$i])
                ->setCellValue('J' . ($i+3), $arr['cols_9'][$i])
                ->setCellValue('K' . ($i+3), $arr['cols_10'][$i])

                ->setCellValue('L' . ($i+3), $arr['cols_11'][$i])
                ->setCellValue('M' . ($i+3), $arr['cols_12'][$i])
                ->setCellValue('N' . ($i+3), $arr['cols_13'][$i])

                ->setCellValue('O' . ($i+3), $jiba[$i]['lairen_jifen'])
                ->setCellValue('P' . ($i+3), $jiba[$i]['xuexiao'])
                ->setCellValue('Q' . ($i+3), $jiba[$i]['order'])
                ->setCellValue('R' . ($i+3), $jiba[$i]['fashu_jifen'])
                ->setCellValue('S' . ($i+3),$jiba[$i]['fashu'])
                ->setCellValue('T' . ($i+3), $jiba[$i]['new_integral'])
                ->setCellValue('U' . ($i+3), $jiba[$i]['jiafen'])
                ->setCellValue('V' . ($i+3), $jiba[$i]['city'])
                ->setCellValue('W' . ($i+3), $jiba[$i]['lairen_jifen']+$jiba[$i]['new_integral']+$jiba[$i]['order']+$jiba[$i]['fashu_jifen']+$jiba[$i]['jiafen']+$jiba[$i]['city'])
            ;
            $objPHPExcel->getActiveSheet()->getRowDimension('' . $i+3)->setRowHeight(25);

        }

        header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
        header('Content-Disposition: attachment;filename="'.$bt.'".xlsx');
        header('Cache-Control: max-age=0');
        // If you're serving to IE 9, then the following may be needed
        header('Cache-Control: max-age=1');

        // If you're serving to IE over SSL, then the following may be needed
        header('Expires: Mon, 26 Jul 1997 05:00:00 GMT'); // Date in the past
        header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . ' GMT'); // always modified
        header('Cache-Control: cache, must-revalidate'); // HTTP/1.1
        header('Pragma: public'); // HTTP/1.0
        $objWriter = \PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
        $objWriter->save('php://output');
        exit;


    }
    /*
    * 积分统计
    * */
    public function statis($ids){
        $dbSea = new \app\admin\model\finance\extract\Season;
        $dbSchD = new \app\admin\model\finance\extract\school\Data;
        $wkDb = new Week();
        $out = new Outreach();
        $jifen = $out->jifen(16);
        $inteArr = array();

        foreach ($jifen[0] as $v){
            $inteArr[]=$v;
        }
        $jibaTotal=0;
        foreach($jifen[1] as $v){
            $jibaTotal+=$v;
        }
        $this->assign('jiba',$inteArr);
        $this->assign('jibaTotal',$jibaTotal);

        $weekInfo = $wkDb->field('name,department')->find($ids);

        $values = $dbSea->where(array('extract_week'=>$ids))->order('id asc')->select()->toArray();
        $uDb=new Admin();
        $dbSch= new \app\admin\model\finance\extract\School;
        $totalTr=0;
        $arr=array();
        $j=0;
        $rankDef=array("1"=>"省会前十","地级前三","县级第一");
        $rows=array();
        $rows['cols_1']=$weekInfo['name'];
        $rows['cols_2']=$this->week_i($ids);
        $rows['cols_3']=$this->ykh_i($ids);
        $rows['cols_4']=$this->task_i($ids);
        $rows['cols_5']=$this->reserve($ids);
        $rows['cols_6']=round($rows['cols_2'],1)+round($rows['cols_3'],1)+round($rows['cols_4'],1)+round($rows['cols_5']['pointer'],1);
        foreach ($values as $key=>$val){
            $data = $dbSch->where(array('season_id'=>$val['id']))->select()->toArray();
            $count=count($data);

            $arr['cols_1'][$totalTr]['row']=$count;
            $arr['cols_1'][$totalTr]['val']=$val['season_time'];
            $arr['cols_2'][$totalTr]['row']=$count;
            $arr['cols_2'][$totalTr]['val']=$val['province_text'].' '.$val['city_text'].' '.$val['area_text'];
            $arr['cols_3'][$totalTr]['row']=$count;
            $arr['cols_3'][$totalTr]['val']=$this->get_fenlei($val['province'],$val['area_text']);
            $arr['cols_4'][$totalTr]['row']=$count;
            $arr['cols_4'][$totalTr]['val']=$this->get_lecturer($val['lecturer_id']);
            $arr['cols_5'][$totalTr]['row']=$count;
            $arr['cols_5'][$totalTr]['val']=$this->get_subject($val['subject_id']);
            $arr['cols_6'][$totalTr]['row']=$count;
            $arr['cols_6'][$totalTr]['val']=$val['reg_level'].'类';
            if ($data){
                $info=array();
               foreach($data as $v){
                   $arr['cols_7'][$j]=$this->get_school($v['school_id']);
                   $info= $dbSchD->where(array('extract_school'=>$v['id'],'type'=>1))->field('userid')->select()->toArray();


                   if ($info){
                       $uname=[];
                       foreach ($info as $d){
                           $a='';
                           if ($d['userid']!=null) {
                               $a=$uDb->field('username,is_zhengshi')->where(array('userid'=>$d['userid']))->find();
                               $uname[]=$a['username'].'/'.($a['is_zhengshi']==1 ? '新外联' : '老外联');
                           }
                       }
                       $arr['cols_8'][$j]=implode('-',$uname);

                   }else{
                       $arr['cols_8'][$j]='';
                   }
                   $arr['cols_9'][$j]= $v['level']==null ? '': $v['level'].'类';
                   $arr['cols_10'][$j]= $rankDef[$v['ranking_level']==null ? "1" : $v['ranking_level']];
                   $arr['cols_11'][$j]= $v['coming_num'];
                   $arr['cols_12'][$j]= $v['gift_books'];
                   $arr['cols_13'][$j]= $v['people_num'];

                   $j++;
               }

            }
            $totalTr+=count($data);

        }
        $authList = $this->authList();
        $rows['title']=$authList[$weekInfo['department']]['name'];
        $this->assign('rows',$rows);
       /* echo '<pre>';
        var_dump($arr);*/
        $this->assign('arr',$arr);

        /*
         * 计算每列所占列数
         * */

        $this->assign('tr',$totalTr);

        //计算总共多少列

        /*
         *
         * field
         * array{
         *  'season_time'场次时间
         *  province  city area  地区
         *  地区分类  地级市 县级
         * lecturer_id 讲师
         *   subject_id 科目
         * reg_level 地区分类
         * 学校名称 school表中获得 array{ school_id学校名称  外联信息 school_data表 分新外联 学校分类}
         *
         *
         * }
         * */
        return $this->view->fetch();

    }
    //预定积分
    protected function reserve($id){
        $pointer = 0;
        $wDb = new Week();
        $info = $wDb->find($id);
        $arr=array();

        //会场无事故故积分
        $integral_accident=$info['integral_accident'];
        $arr['index_1']=0;

        if ($integral_accident==1){
            $pointer+=20;
            $arr['index_1']=20;
        }
        //学校建设积分
        if ($info['integral_complaint']==1){
            $pointer+=20;
            $arr['index_2']=20;
        }else{
            $pointer+=10;
            $arr['index_2']=10;
        }
        //公众号加关注积分
        $dbSea = new \app\admin\model\finance\extract\Season;
        $values = $dbSea->where(array('extract_week'=>$id))->order('id asc')->select()->toArray();
        $arr['index_3']=0;

        if ($info['integral_follow'] >0 ){
            $dbSch= new \app\admin\model\finance\extract\School;

            $follow_people=0;
            foreach ($values as $k=>$v){
                $oSch = $dbSch->where(array('season_id'=>$v['id']))->select()->toArray();
                if ($oSch){
                    $onum = array_sum(array_column($oSch,'people_num'));
                    $follow_people+=$onum;
                }
            }
            $centage=0;
            //百分比
            if ($follow_people > 0) {
                $centage = round($info['integral_follow'] / $follow_people, 2) * 100;
            }
            if ($centage >=80){
                $pointer+=20;
                $arr['index_3']=20;
            }
            if ($centage>=50 && $centage < 80){
                $pointer+=round(0.2*$centage,1);
                $arr['index_3']=round(0.2*$centage,1);
            }
        }
        //取预定积分
        if ($info['integral_reserve']<=0){
            $pointer+=10;
            $arr['index_4']=10;


        }else{
            $pointer = round($info['integral_take']/$info['integral_reserve']*20,1);
            $arr['index_4']=round($info['integral_take']/$info['integral_reserve']*20,1);

        }
        //会后图书销售积分
        $dbRound = new Round();
        $arr['index_5']=0;

        foreach ($values as $v){
            $roundInfo = $dbRound->where(array('season_id'=>$v['id']))->select()->toArray();
            $money = 0;
            if ($roundInfo) {
                foreach ($roundInfo as $v) {
                    $money += $v['sales_price'] * $v['pricing_num'];

                }
                if ($money >= 30000) {
                    $pointer += 30;
                    $arr['index_5']=30;
                } else if ($money >= 20000) {
                    $pointer += 20;
                    $arr['index_5']=20;

                } else if ($money >= 10000) {
                    $pointer += 10;
                    $arr['index_5']=10;

                }
            }

        }
        $arr['index_6']=0;
        $subDef = array("1"=>"会场赠书不够","赠书或产品发航空","暴场","和家长打架","因未备案被查");
        //减分项
        if ($info['integral_subtraction']!=null){
            $subStr='';
            $subtra = explode(',',$info['integral_subtraction']);
            foreach ($subtra as $v){
                $pointer-=30;
                $subStr.=$subDef[$v].', ';
            }
            $arr['index_6']=$subStr.'累计减分-'.count($subtra)*30;

        }
        return ['pointer'=>$pointer,'arr'=>$arr];
    }
    //周任务积分
    protected function task_i($id){
        $dbSea = new \app\admin\model\finance\extract\Season;

        $values = $dbSea->where(array('extract_week'=>$id))->order('id asc')->select()->toArray();
        $dbSch= new \app\admin\model\finance\extract\School;
        $dbSchD = new \app\admin\model\finance\extract\school\Data;
        $nums = count($values);
        $total=0;
        $type=array();
        foreach ($values as $k=>$v){
            $oSch = $dbSch->where(array('season_id'=>$v['id']))->select()->toArray();
            $type[]=$v['reg_level'];
            if ($oSch){
                foreach ($oSch as $d=>$val) {
                    $arrs= $dbSchD->where(array('extract_school'=>$val['id'],'type'=>2))->field('price,num')->select()->toArray();
                    foreach ($arrs as $money) {
                        $total+=$money['price']*$money['num'];

                    }
                }
            }

        }
        if(empty($type)) return 0;
        $hots = array_count_values($type);
        krsort($hots);



        $key='';
        if ($hots) $key = array_search(max($hots),$hots);

        if ($key=="A") {
            if (intval($total / 2986) > 250) {
                if($nums > 6){
                    return 30;

                }else{
                    return 60;

                }
            }
        }
        if (intval($total/3686) > 153){
            $arrOne = ['A'=>30,'B'=>40,'C'=>60];
            if($nums > 6){
                return $arrOne[$key]/2;

            }else{
                return $arrOne[$key];

            }
        }
        if (intval($total/3686) > 116){
            $arrOne = ['A'=>20,'B'=>30,'C'=>40];
            if($nums > 6){
                return $arrOne[$key]/2;

            }else{
                return $arrOne[$key];

            }
        }
        if (intval($total/2986) > 100){
            $arrOne = ['A'=>0,'B'=>10,'C'=>20];
            if($nums > 6){
                return $arrOne[$key]/2;

            }else{
                return $arrOne[$key];

            }
        }
        return 0;

        //当前分公司周次总进钱，折合。统计，每场会+学校

    }
    //获取场次来人数
    //周开场词积分
    protected function week_i($id){
        if (!$id) return false;
        $dbSea = new \app\admin\model\finance\extract\Season;
        $dbSchD = new \app\admin\model\finance\extract\school\Data;
        $values = $dbSea->where(array('extract_week'=>$id))->order('id asc')->select()->toArray();
        $dbSch= new \app\admin\model\finance\extract\School;
        $pointer = 0;

        /*
         * 开4场，基本积分每场10分，
         * 开5场基本积分每场15分，
         * 开6场达到5场销售标准每场加15分，
         * 多开场销售15套以上，不计分，销售低于15套，每场扣15分
         * 计算单场发书超过1800册，不加分。单场来人超过1500人，扣20分
         * */

        foreach ($values as $k=>$v){
            $oSch = $dbSch->where(array('season_id'=>$v['id']))->select()->toArray();
            if ($oSch){
                $onum = array_sum(array_column($oSch,'people_num'));

                $values[$k]['people_num']=$onum;

            }else{
                $values[$k]['people_num']=0;
            }
        }

        $nums = count($values);


        //计算单场来人数量
        if ($nums==4){
            foreach ($values as $v){

                    if ($v['gift_books'] <=1800){
                        $pointer+=10;
                    }


            }

        }elseif($nums==5){
            foreach ($values as $v){

                    if ($v['gift_books'] <=1800){
                        $pointer+=15;
                    }


            }
        }elseif ($nums==6){

            //获取最后一场
            foreach ($values as $k=>$v){
                if ($k <=4){

                    if ($v['gift_books'] <=1800){
                        $pointer+=15;
                    }

                }
            }

            $last = end($values);

            if ($v['gift_books'] <=1800) {

                $lid = $last['id'];
                $oneSch = $dbSch->where(array('season_id' => $lid))->find()->toArray();
                if ($oneSch) {
                    $sid = $oneSch['id'];
                    $numm = $dbSchD->where(array('extract_school' => $sid))->select()->toArray();
                    if ($numm) {
                        //计算几次的数量是否达到15套销售标准，共计，N个学校
                        $ns = array_sum(array_column($numm, 'num'));
                        if ($ns >= 15) {
                            $pointer += 15;
                        }
                    }

                }
            }

        }elseif($nums > 6){
            /*
             * 前五场每场15积分，超过6场后，则需要达到15套销售标准。 在学校中调取数据
             * */
            foreach ($values as $k=>$v){
                if ($k <=4){

                        if ($v['gift_books'] <=1800){
                            $pointer+=15;
                        }

                }
            }

            $dbSchD = new \app\admin\model\finance\extract\school\Data;
            foreach ($values as $k=>$value) {
                if ($k > 4) {

                        if ($value['gift_books'] <=1800) {
                            $oneSch = $dbSch->where(array('season_id' => $value['id']))->find();

                            if ($oneSch) {
                                $sid = $oneSch['id'];
                                $numm = $dbSchD->where(array('extract_school' => $sid,'type'=>2))->select()->toArray();
                                if ($numm) {
                                    $ns = array_sum(array_column($numm, 'num'));
                                    if ($ns < 15) $pointer -= 15;;
                                }

                            }
                        }

                }
            }
            /*foreach 循环结束*/

        }
        //判断来人数,不管怎么样先走上面的条件
        foreach ($values as $v){
            if ($v['people_num'] > 850){
                $pointer-=20;
            }
        }
        /*
         * 每场,初一、高一、中考、高考、地级来人400~600人，每场加10分，少于300人或多余800人不加分。北京、天津、上海来人200~300人，每场加10分，
         * 少于100人或多余400人不加分。
         *
         * 实现逻辑 判断是否是考题开奖产品， 第二部判断地级，县级
         * */
        $areaList = $dbSea->getProvinceOrderList();

        foreach ($values as $k=>$v){
            //考题开奖产品
            if ($v['subject_id']==6){
                if(in_array($v['province'],array(1,19,801))){
                    if(in_array($v['province'],array(1,19,801))){
                        if ($v['people_num'] >=300 && $v['people_num'] <=400){
                            $pointer+=10;
                        }
                    }else{
                        if ($v['people_num'] >=500 && $v['people_num'] <=800){
                            $pointer+=10;
                        }
                    }

                }
            }else{
                $sub_arae = mb_substr($areaList[$v['area']],-1,1,'utf8');
                //北京，天津，上海,200-300人之间加分
                if(in_array($v['province'],array(1,19,801))){
                    if ($v['people_num'] >=200 && $v['people_num'] <=300){
                        $pointer+=10;
                    }
                }else{
                    if ($sub_arae=="区"){
                        if ($v['people_num'] >=400 && $v['people_num'] <=600){
                            $pointer+=10;
                        }
                    }else{
                        if ($v['people_num'] >=500 && $v['people_num'] <=800){
                            $pointer+=10;
                        }
                    }
                }


            }
        }

        return $pointer;
    }


}